package com.mindainfo.configCenter.base.dao.impl;

import com.mindainfo.configCenter.base.dao.IBaseDao;
import com.mongodb.MongoClient;
import org.bson.types.ObjectId;
import org.mongodb.morphia.Datastore;
import org.mongodb.morphia.Key;


import javax.annotation.Resource;
import java.lang.reflect.ParameterizedType;
import java.lang.reflect.Type;

/**
 * Created by MD-01 on 2016/11/11.
 */
public class BaseDaoImpl<T> implements IBaseDao<T> {

    private Class<T> entityClass;

    @Resource
    private MorphiaDao morphiaDao;

    @SuppressWarnings("unchecked")
    public BaseDaoImpl() {
        Type genType = getClass().getGenericSuperclass();
        Type[] params = ((ParameterizedType) genType).getActualTypeArguments();
        entityClass = (Class<T>) params[0];
    }


    public String save(T t) {
        Key<T> key = getDatastore().save(t);
        return key.getId().toString();
    }

    @Override
    public int delete(T t) {

        return getDatastore().delete(t).getN();
    }

    @Override
    public T get(String objectId) {

        return getDatastore().get(entityClass,new ObjectId(objectId));
    }

    @Override
    public int delete(String objectId) {

        return getDatastore().delete(entityClass,new ObjectId(objectId)).getN();
    }

    /**
     * 获得操作mongo的Datastore对象
     *
     * @return
     */
    public Datastore getDatastore() {

        return morphiaDao.getDatastore();
    }

    public MongoClient getMongoClient(){
        return morphiaDao.getMongoClient();
    }

}
